﻿//  Copyright (c) 2009 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace DNA.Mvc.jQuery
{
    public static class CrumbExtensions
    {
        public static MvcHtmlString Crumb(this AjaxHelper helper, IHierarchicalNodeProvider provider, string currentNodeKey)
        {
            return helper.Crumb(provider, currentNodeKey, string.Empty);
        }

        public static MvcHtmlString Crumb(this AjaxHelper helper, IHierarchicalNodeProvider provider, string currentNodeKey, string appendText)
        {
            if (provider == null)
                throw new ArgumentNullException("provider");

            if (string.IsNullOrEmpty(currentNodeKey))
                throw new ArgumentNullException("currentNodeKey");

            var builder = new NodeUIBuilder();

            var current = provider.FindNodeFormKey(currentNodeKey);
            if (current != null)
            {
                string icon = "ui-icon ui-icon-carat-1-e";
                string nodeStyle = "float:left;margin-right:5px;";
                builder.WriteBeginTag("ul", new { Class = "ui-helper-reset dna-ui-crumb" });

                List<HierarchicalNode> _array = new List<HierarchicalNode>();

                for (var node2 = current.ParentNode; node2 != null; node2 = node2.ParentNode)
                    _array.Add(node2);
               // _array.Add(provider.RootNode);

                if (_array.Count > 0)
                    _array.Reverse();

                foreach (var node in _array)
                {
                    builder.WriteNode(node, new { style = nodeStyle });
                    builder.WriteIconNode(icon, new { style = nodeStyle });
                }
                builder.WriteNode(current, new { style = nodeStyle });

                if (!string.IsNullOrEmpty(appendText))
                {
                    builder.WriteIconNode(icon, new { style = nodeStyle });
                    builder.WriteNode(new HierarchicalNode() { Title = appendText, Description = appendText }, new { style = nodeStyle });
                }

                builder.WriteEndTag("ul");
            }
            return MvcHtmlString.Create(builder.ToString());
        }
    }
}
